from PyQt6.QtWidgets import QApplication
from window_capture import WindowCapture
import sys
import subprocess
import os
import time
import signal
import atexit

def start_audio_capture(show_console=True):
    """启动音频捕获子进程
    
    Args:
        show_console (bool): 是否显示控制台窗口
    """
    try:
        # 检查cap-audio.exe是否存在
        audio_exe_path = os.path.join("cap-audio", "cap-audio.exe")
        if not os.path.exists(audio_exe_path):
            print(f"警告: 找不到音频捕获程序: {audio_exe_path}")
            print("请确保cap-audio目录中包含cap-audio.exe文件")
            return None
        
        # 检查是否已经有cap-audio进程在运行
        try:
            # 尝试连接到现有的cap-audio进程（如果有的话）
            import psutil
            for proc in psutil.process_iter(['pid', 'name', 'exe']):
                if proc.info['name'] == 'cap-audio.exe' and 'cap-audio' in proc.info['exe']:
                    print(f"发现已运行的音频捕获程序，PID: {proc.info['pid']}")
                    return proc
        except ImportError:
            pass  # psutil不可用，继续启动新进程
        
        # 启动子进程
        print(f"正在启动音频捕获程序: {audio_exe_path}")
        
        # 根据show_console参数决定是否显示控制台窗口
        if os.name == 'nt':  # Windows系统
            if show_console:
                # 显示控制台窗口
                creation_flags = subprocess.CREATE_NEW_CONSOLE
                print("✓ 控制台窗口将显示")
            else:
                # 隐藏控制台窗口
                creation_flags = subprocess.CREATE_NO_WINDOW
                print("✓ 控制台窗口已隐藏")
        else:
            # 非Windows系统
            creation_flags = 0
        
        process = subprocess.Popen(
            [audio_exe_path],
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            creationflags=creation_flags,
            cwd=os.path.dirname(audio_exe_path)  # 设置工作目录
        )
        
        # 等待一下确保进程启动
        time.sleep(2)
        
        if process.poll() is None:
            print(f"音频捕获程序启动成功，PID: {process.pid}")
            return process
        else:
            # 检查进程输出以了解失败原因
            stdout, stderr = process.communicate()
            if stdout:
                print(f"音频捕获程序输出: {stdout.decode('utf-8', errors='ignore')}")
            if stderr:
                print(f"音频捕获程序错误: {stderr.decode('utf-8', errors='ignore')}")
            print("音频捕获程序启动失败")
            return None
            
    except Exception as e:
        print(f"启动音频捕获程序时出错: {e}")
        return None

def check_audio_process_status(process):
    """检查音频捕获进程状态"""
    if not process:
        return False
    
    if process.poll() is None:
        return True
    else:
        print("音频捕获程序已停止运行")
        return False

def toggle_console_window(process, show=True):
    """切换控制台窗口显示/隐藏
    
    Args:
        process: 子进程对象
        show (bool): True显示窗口，False隐藏窗口
    """
    if not process or process.poll() is not None:
        print("进程未运行，无法控制窗口")
        return False
    
    if os.name != 'nt':
        print("此功能仅在Windows系统上可用")
        return False
    
    try:
        import win32gui
        import win32con
        import win32process
        
        # 查找进程的主窗口
        def enum_windows_callback(hwnd, windows):
            try:
                _, pid = win32process.GetWindowThreadProcessId(hwnd)
                if pid == process.pid:
                    windows.append(hwnd)
            except:
                pass
            return True
        
        windows = []
        win32gui.EnumWindows(enum_windows_callback, windows)
        
        if not windows:
            print("未找到进程的控制台窗口")
            return False
        
        # 控制窗口显示/隐藏
        for hwnd in windows:
            if show:
                win32gui.ShowWindow(hwnd, win32con.SW_SHOW)
                print("✓ 控制台窗口已显示")
            else:
                win32gui.ShowWindow(hwnd, win32con.SW_HIDE)
                print("✓ 控制台窗口已隐藏")
        
        return True
        
    except ImportError:
        print("需要安装 pywin32 库来控制窗口显示/隐藏")
        print("请运行: pip install pywin32")
        return False
    except Exception as e:
        print(f"控制窗口显示/隐藏时出错: {e}")
        return False

def cleanup_audio_process(process):
    """清理音频捕获进程"""
    if process and process.poll() is None:
        print("正在关闭音频捕获程序...")
        try:
            process.terminate()
            process.wait(timeout=5)
            print("音频捕获程序已正常关闭")
        except subprocess.TimeoutExpired:
            process.kill()
            print("强制关闭音频捕获程序")
        except Exception as e:
            print(f"关闭音频捕获程序时出错: {e}")

def main():
    """主函数"""
    print("=" * 50)
    print("Window Capture 启动中...")
    print("=" * 50)
    
    show_console = False
    
    # 先启动音频捕获子进程
    audio_process = start_audio_capture(show_console=show_console)
    
    if audio_process:
        print("✓ 音频捕获程序已启动")
        
        # 如果用户选择隐藏控制台，但进程启动时显示了，则隐藏它
        if not show_console and os.name == 'nt':
            print("正在隐藏控制台窗口...")
            time.sleep(1)  # 等待窗口创建
            toggle_console_window(audio_process, show=False)
    else:
        print("⚠ 音频捕获程序启动失败，但主程序将继续运行")
    
    print("正在启动主窗口...")
    
    # 注册清理函数
    if audio_process:
        atexit.register(cleanup_audio_process, audio_process)
    
    app = QApplication(sys.argv)
    
    # 设置应用程序样式
    app.setStyle('Fusion')
    
    # 创建主窗口
    window = WindowCapture()
    window.show()
    
    # 运行应用程序
    try:
        # 设置应用程序退出处理
        def on_about_to_quit():
            print("应用程序即将退出...")
            if audio_process:
                cleanup_audio_process(audio_process)
        
        app.aboutToQuit.connect(on_about_to_quit)
        
        # 运行应用程序
        result = app.exec()
        print(f"应用程序退出，返回值: {result}")
        return result
        
    except KeyboardInterrupt:
        print("\n收到中断信号，正在退出...")
        return 0
    except Exception as e:
        print(f"应用程序运行出错: {e}")
        return 1
    finally:
        # 程序退出时关闭子进程
        if audio_process:
            cleanup_audio_process(audio_process)

if __name__ == "__main__":
    main()